<template>
	<div>
		<!-- 报名按钮 -->
		<!-- <Button type="primary" @click="openModal">报名</Button> -->

		<!-- 弹窗 -->
		<Modal v-model="innerVisible" :title="$t('page.activity.add_activity_goods')" :width="900" @on-ok="handleOk">
			<Form ref="formDynamic" :model="formDynamic" class="attrFrom" @submit.native.prevent>
				<Row :gutter="24">
		
					<Col span="24">
					
					<h3 style="margin-top: 20px;line-height: 30px;">{{$t('page.activity.information')}}</h3>
					<Table border :columns="goodsColumns" :data="[radioProduct]">
		
						<template slot="image" slot-scope="{ row }">
						    <viewer>
						      <div class="tabBox_img">
						        <img v-lazy="row.image" width="60" />
						      </div>
						    </viewer>
						  </template>
					</Table>
					<h3 style="margin-top: 20px;line-height: 30px;">{{$t('page.activity.configure')}} ({{ radioProduct.store_name }})</h3>

					<Table border :columns="skuColumns" :data="radioProduct.skuList" editable max-height="500">
									
						<template slot="activity_price" slot-scope="{ row, index }">
						    <Input
						      :value="radioProduct.skuList[index].activity_price"
						      :placeholder="$t('page.activity.event_price')"
						      @input="val => radioProduct.skuList[index].activity_price = val"
							  :disabled="radioProduct.skuList[index].stock == 0"
						    />
						</template>
						<template slot="warehouse" slot-scope="{ row, index }">
						    <div v-for="(warehouse, wIndex) in row.product_stock_info" :key="wIndex">
						                {{warehouse.warehouse}}
						                <div style="margin: 10px 0;" v-if="wIndex < row.product_stock_info.length - 1"></div>
						              </div>
						</template>
						<template slot="stock" slot-scope="{ row, index }">
						    <div v-for="(warehouse, wIndex) in row.product_stock_info" :key="wIndex">
						                <Input
						                  :value="warehouse.stock"
						                  disabled
						                />
						                <div style="margin: 10px 0;" v-if="wIndex < row.product_stock_info.length - 1"></div>
						              </div>
						</template>
						<template slot="activity_stock" slot-scope="{ row, index }">
						  <div v-for="(warehouse, wIndex) in row.product_stock_info" :key="wIndex">
						    <Input
						      :value="getActivityStockValue(row, wIndex)"
						      :placeholder="$t('page.activity.event_stock')"
						      @input="val => handleStockInput(val, index, wIndex)"
						      :disabled="warehouse.stock == 0"
						      type="number"
						      min="0"
						      :max="warehouse.stock"
						    />
						    <div style="margin: 10px 0;" v-if="wIndex < row.product_stock_info.length - 1"></div>
						  </div>
						</template>
					</Table>
					</Col>
				</Row>
			</Form>
			<!-- 自定义底部按钮 -->
			<template #footer>
				<div class="custom-modal-footer">
					<Button type="primary" size="large" @click="submit" v-if="radioProduct.status == 0">
						提交
					</Button>
				</div>
			</template>
		</Modal>
	</div>
</template>

<script>
	import {
		getGoodListApi,
		getActivityGoodSku,
		getActivityProductDetail,
		createActivityProductApi
	} from '@/api/capital';
	export default {
		name: "SignupModal",
		props: {
			visible: {
				type: Boolean,
				default: false
			},
			activityGoodId: {
				type: [String, Number],
				default: null
			}
		},
		data() {
			return {
				innerVisible: false,
				selectedGoods: null,
				goodsList: [],
				total: 0,
				formDynamic:{},
				// radioProduct: {},
				radioProduct: {
					skuList: []
				},
				skuList: [],
				// goodsColumns: [{
				// 		title: "ID",
				// 		key: "id",
				// 		width: 80
				// 	},
				// 	{
				// 		title: "商品名",
				// 		key: "store_name"
				// 	},
				// 	{
				// 		title: "缩略图",
				// 		slot: "image",
					
				// 	},
				// 	{
				// 		title: "价格",
				// 		key: "price"
				// 	},
				// 	{
				// 		title: "总库存",
				// 		key: "stock"
				// 	}
				// ],
				// skuColumns: [{
				// 		title: "SKU ID",
				// 		key: "id",
				// 		width: 80
				// 	},
				// 	{
				// 		title: "规格",
				// 		key: "suk"
				// 	},
				// 	{
				// 		title: "库存",
				// 		key: "stock"
				// 	},
				// 	{
				// 		title: "原价",
				// 		key: "price"
				// 	},
				// 	{
				// 		title: "活动价",
				// 		key: "activity_price",
				// 		slot: "activity_price"
				// 	},
				// 	{
				// 		title: "活动库存",
				// 		key: "activity_stock",
				// 		slot: "activity_stock"
				// 	}
				// ],
			};
		},
		computed:{
			goodsColumns(){
				return [{
					title: "ID",
					key: "id",
					width: 80
				},
				{
					title: $t('page.product.product_name'),
					key: "store_name"
				},
				{
					title: $t('page.product.image'),
					slot: "image",
				
				},
				{
					title: $t('page.product.price'),
					key: "price"
				},
				{
					title: $t('page.stock.total_inventory'),
					key: "stock"
				}
			]
			}, 
			skuColumns(){
				return [{
						title: "SKU ID",
						key: "id",
						width: 80
					},
					{
						title: $t('page.product.specification'),
						key: "suk"
					},
					{
						title: $t('page.product.original_price'),
						key: "price"
					},
					{
						title: $t('page.activity.event_price_title'),
						key: "activity_price",
						slot: "activity_price"
					},
					{
						title: $t('page.stock.warehouse'),
						key: "warehouse",
						slot: "warehouse"
					},
					{
						title: $t('page.stock.stock'),
						key: "stock",
						slot: "stock"
					},
					{
						title: $t('page.activity.event_stock_title'),
						key: "activity_stock",
						slot: "activity_stock"
					}
				]
			}
		},
		watch: {
			visible(val) {
				this.innerVisible = val
				if (val) {
					console.log("打开弹窗, 活动商品ID:", this.activityGoodId);
					// 可以用 this.activityId 去请求商品
					this.getActivityGoodInfo(this.activityGoodId)
				}
			},
			innerVisible(val) {
				this.$emit("update:visible", val)
			}
		},
		methods: {
			// 获取活动库存显示值
			 getActivityStockValue(row, warehouseIndex) {
			   // 确保 activity_stock 是数组
			   if (!Array.isArray(row.activity_stock)) {
			     if (typeof row.activity_stock === 'number') {
			       return row.activity_stock;
			     }
			     return 0;
			   }
			   
			   // 返回对应仓库的活动库存
			   return row.activity_stock[warehouseIndex] !== undefined ? row.activity_stock[warehouseIndex] : 0;
			 },
			 // 处理活动库存输入
			 handleStockInput(val, index, warehouseIndex) {
			   const numVal = parseInt(val) || 0;
			   const maxStock = this.radioProduct.skuList[index].product_stock_info[warehouseIndex].stock;
			   
			   // 限制不能超过最大库存
			   // const finalVal = Math.min(numVal, maxStock);
			   const finalVal = numVal
			   
			   // 确保 activity_stock 是数组
			   if (!Array.isArray(this.radioProduct.skuList[index].activity_stock)) {
			     this.$set(this.radioProduct.skuList[index], 'activity_stock', 
			       new Array(this.radioProduct.skuList[index].product_stock_info.length).fill(0));
			   }
			   
			   this.$set(this.radioProduct.skuList[index].activity_stock, warehouseIndex, finalVal);
			 },
			getActivityGoodInfo(id){
				//获取供应活动商品
				getActivityProductDetail(id)
					.then(async (res) => {
						this.radioProduct = res.data.info
						let stock = 0
						this.radioProduct.skuList.forEach(item => {
							stock += item.stock
						})
						this.radioProduct.stock = stock
						console.log(this.radioProduct.status)
					})
					.catch((res) => {
						this.$Message.error(res.msg)
					})
			},
			// submit() {
			// 	if(this.radioProduct.status != 0){
			// 		this.$Message.success("无法对已审核的商品进行更改");
			// 	}
			// 	let data = {
			// 		product_id:this.radioProduct.id,
			// 		activity_id:this.activityGoodId,
			// 		activity_product_id:this.activityGoodId,
			// 		sku_list:this.radioProduct.skuList,
			// 	}
			// 	let tijiao = 1
			// 	this.radioProduct.skuList.forEach(item=>{
			// 		if(item.activity_stock > item.stock){
			// 			this.$Message.error("库存不足");
			// 			tijiao = 2
			// 		}
			// 	})
			// 	if(tijiao == 1){
			// 		createActivityProductApi(data)
			// 		    .then((res) => {
			// 		        this.$Message.success(res.msg);
			// 				this.innerVisible = false
			// 		    })
			// 		    .catch((res) => {
			// 		        this.modal_loading = false;
			// 		        this.$Message.error(res.msg);
			// 		    });
			// 	}
				
			// },
			// 提交前确保数据格式正确
			  submit() {
			    // 确保所有sku的activity_stock都是数组格式
			    this.radioProduct.skuList.forEach(sku => {
			      if (!Array.isArray(sku.activity_stock)) {
			        if (typeof sku.activity_stock === 'number') {
			          // 如果是数字，转换为与仓库数量相同的数组
			          sku.activity_stock = new Array(sku.product_stock_info.length).fill(sku.activity_stock);
			        } else {
			          // 否则初始化为0数组
			          sku.activity_stock = new Array(sku.product_stock_info.length).fill(0);
			        }
			      }
			    });
			    let data = {
			      product_id: this.radioProduct.id,
			      activity_id: parseInt(this.activityGoodId),
				  activity_product_id:this.activityGoodId,
			      sku_list: this.radioProduct.skuList,
			    }
			    
			    // 验证逻辑
			    let isValid = true;
			    this.radioProduct.skuList.forEach(item => {
			      if (Array.isArray(item.activity_stock)) {
			        item.activity_stock.forEach((stock, wIndex) => {
			          const maxStock = item.product_stock_info[wIndex].stock;

					  if(item.product_stock_info[wIndex].stock > 0){
						  if(stock <= 0){
						  		this.$Message.error(`${item.suk} 的活动库存不能小于等于0`);
						  		isValid = false;
						  }
						  if (stock > maxStock) {
						    this.$Message.error(`${item.suk} 的活动库存不能超过可用库存`);
						    isValid = false;
						  }
					  }
					  
			        });
			      }
			    });
				console.log("dddd:",data)
			
			    if (isValid) {
			      createActivityProductApi(data)
			        .then((res) => {
			          this.$Message.success(res.msg);
			          this.innerVisible = false
			          this.$emit('success')
			        })
			        .catch((res) => {
			          this.$Message.error(res.msg);
			        });
			    }
			  },
			closeModal() {
				this.innerVisible = false
			},
			handleOk() {
				this.$emit('update:modalVisible', false);
				// 处理确认逻辑
			},
		}
	};
</script>